﻿using System;
using System.Reflection;

namespace DTO
{
    /// <summary>
    /// Copy thuộc tính của object
    /// </summary>
    /// <typeparam name="T">Object cho</typeparam>
    /// <typeparam name="U">Object nhận</typeparam>
    public class CopyObject<T, U>
    {
        /// <summary>
        /// Copy thuộc tính của object này sang object khác
        /// </summary>
        /// <param name="source">Object cho</param>
        /// <param name="dest">Object nhận</param>
        public static void Copy(T source, U dest)
        {
            // Lấy kiểu của object cho và object nhận
            Type sourceType = source.GetType();
            Type destType = source.GetType();

            foreach (PropertyInfo sc in sourceType.GetProperties())
            {
                foreach (PropertyInfo ds in destType.GetProperties())
                {
                    // Nếu tên hai thuộc tính của object cho và nhận không giống nhau
                    // (tên và kiểu dữ liệu...) thì bỏ qua (tiếp tục vòng lặp)
                    if (!sc.Name.Equals(ds.Name)) continue;

                    if (sc.CanRead && ds.CanWrite)
                    {
                        ds.SetValue(dest, sc.GetValue(source, null), null);
                        break;
                    }
                }
            }
        }
    }
}